export default class Recursion {
  constructor (list, idProp, pIdProp) {
    this.list = list
    this.idProp = idProp
    this.pIdProp = pIdProp
  }
  /**
   * 该方法为私有方法，JS不支持私有方法的声明
   * 设置树形属性用
   */
  setProps (newObject, object) {
    Object.keys(object).forEach(key => {
      if (key !== this.idProp && key !== this.pIdProp) {
        newObject[key] = object[key]
      }
    })
  }
  /**
   * 该方法为私有方法，JS不支持私有方法的声明
   * 递归出子节点
   */
  recursion (pId) {
    const children = []
    this.list.forEach(item => {
      if (item[this.pIdProp] === pId) {
        const treeItem = {}
        treeItem[this.idProp] = item[this.idProp]
        this.setProps(treeItem, item)
        treeItem.children = this.recursion(item[this.idProp])
        children.push(treeItem)
      }
    })
    return children
  }
  /**
   * 共有方法
   * 构建树形菜单
   */
  buildTree () {
    const tree = []
    this.list
      .filter((item) => {
        return item[this.pIdProp] === null
      })
      .forEach((parent) => {
        const treeItem = {}
        treeItem[this.idProp] = parent[this.idProp]
        this.setProps(treeItem, parent)
        treeItem.children = this.recursion(parent[this.idProp])
        tree.push(treeItem)
      })
    return tree
  }
}
